<template>
	<!-- 顶部导航 -->
	<custom-top></custom-top>
	<custom-tab v-model="actIdx"/>
	<!-- 咨询消息 -->
	<view v-if="actIdx==0">
		<view class="cu-list menu-avatar">
			<view class="cu-item"  v-for="(item,index) in textList" @click="handelDetail(item?.objectId,item?.otherId,item?.selfId)">

				<image class="cu-avatar round lg" :src="item?.url" mode="aspectFill"/>
				<view class="content">
					<view class="text-xl">{{item?.name}}</view>
					<view class="text-gray text-sm flex">
						<view class="text-cut">
							{{item?.lastMessage||'暂无消息'}}
						</view>
					</view>
				</view>
				<view class="action flex align-start ">
					<view class="text-grey text-xs margin-bottom-xl">{{ item.lastMessageTime?formatTime(item.lastMessageTime):''}}</view>
					<!-- <view class="cuIcon-notice_forbid_fill text-gray"></view> -->
				</view>
			</view>
		</view>
		<view v-if="textList.length==0" class="nodata flex flex-direction align-center margin-top-xl">
			<image src="/src/static/ym/search.png" mode="aspectFill"></image>
			<view class="text-gray" >
				暂时还没有咨询消息
			</view>
			<view class="text-lg margin-top-sm" style="color: #aaa;">
				有烦恼？找专业人士聊聊吧！
			</view>
		</view>
	</view>
	<!-- 系统通知 -->
	<view v-else>
		<view class="cu-list menu padding-top padding-right">
			<view class="cu-item arrow" v-for="(item,index) in SysMsg" @click="handelDetailSys(item)">
				<view class="content padding">
					<image :src="item?.url" mode="aspectFilt" class="round" style="margin-right: 30upx;height: 80upx;width: 80upx; padding: 5upx;"></image>
					<text class="text-black text-lg text-bold text-center">{{item?.name}}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { getChatList, updateChatList } from '@/api/chat';
import type{ chaterType } from '@/model/chat';
import { onLoad, onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import { ref } from 'vue';
import type{ Ref } from 'vue';
import { useAccount } from '@/store/user';
import { getUserInfo } from '@/api/user';
const account = useAccount()

// 系统通知
const SysMsg = [
	{"url":"../../static/ym/icon2.png","name":"系统通知","userId":"sys1"},
	{"url":"../../static/ym/icon3.png","name":"服务通知","userId":"sys2"},
	{"url":"../../static/ym/icon1.png","name":"我的提问","userId":"sys3"},
];
// 咨询消息
const textList:Ref<Array<chaterType>> = ref([])

// 切换tab
const actIdx = ref(0);
// 咨询详情
const handelDetail = (objectId:string,otherid:string,selfid:string)=>{
	uni.navigateTo({
		url: `/pages/MoodBottle/detail?objectId=${objectId}&otherid=${otherid}&selfid=${selfid}`
	})
}
// 系统通知详情
const handelDetailSys = (item:any)=>{
	uni.navigateTo({
		url: `/pages/MoodBottle/detailSys?userId=${item.userId}`
	})
}

let isFetching = false; // 添加请求状态锁

const fetchData = async () => {
    if (isFetching) return;
    isFetching = true;
    try {
        let res = await getChatList(account.userinfo?.objectId||'');
        console.log('获取聊天用户列表', res);
        let list = res.data.results || [];
        const newItems = [];
        for (const item of list) {
            let id = item.otherId === account.userinfo?.objectId ? item.selfId : item.otherId;
            // let user = await getUserInfo(id);
            // console.log('获取用户详情',user);
            // item.name = user.data.name;
            // 确保和模板对应，统一使用 url
            // item.url =  user.data.avatar;
			// let update = await updateChatList(item.objectId,{ name:item.name,url:item.url }as chaterType)
			// console.log('更新chat表name，url信息',update);
            newItems.push(item);
        }
        textList.value = newItems;
    } catch (error) {
        console.error('获取数据失败:', error);
    } finally {
        isFetching = false;
    }
}
// 格式化时间显示
const formatTime = (timestamp: number): string => {
    const date = new Date(timestamp);
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};
// 移除 onLoad 中的调用
// onLoad(async()=>{
//     await fetchData();
// })

onShow(async () => {
    await fetchData();
})

onPullDownRefresh(async () => {
    await fetchData();
    uni.stopPullDownRefresh();
})

</script>

<style lang="scss">
page {
	background-color: #fff;
}
.nodata{
	image{
		height: 700upx;
		width: 500upx;
	}
}
.cu-item:after{
	border-bottom:0px !important;
}
</style>